<template>
	<view>
		<f-navbar title="新增入库" navbarType="1"> </f-navbar>
		<view class="add-collection">
			<view class="form">
				<u--form labelPosition="left" labelWidth="100"  :model="form" :rules="rules" ref="uForm">
					<u-form-item required label="来源" prop="source" borderBottom>
						<LSelect border="none" v-model="form.source" dataKey="label" dataValue="value"
							:localdata="source_type"></LSelect>
					</u-form-item>
					<u-form-item required label="入库地点" prop="receiptLocationId" borderBottom>
						<LSelect border="none" v-model="form.receiptLocationId" dataKey="transferStationName"
							dataValue="id" :localdata="transferAllList" :disabled="true"></LSelect>
					</u-form-item>
					<u-form-item label="入库日期" prop="indate" required borderBottom labelWidth="100">
						<picker mode="date" v-model="form.indate" @change="transportationTimeChange">
							<view class="box-item">
								<view v-if="form.indate">{{
					  formatDate(form.indate, "Y-m-d")
					}}</view>
								<view class="item-text" style="color: #c0c4cc" v-else>请选择</view>
							</view>
						</picker>
					</u-form-item>
					<template v-if="form.source == '0'">
						<u-form-item required label="选择司机" borderBottom>
							<LSelect border="none" v-model="selectDriverId" dataKey="name" dataValue="id"
								:localdata="driverAllList" @change="getOrderListByReceipt"></LSelect>
						</u-form-item>
						<u-form-item required label="入库油品" borderBottom labelWidth="100">
							<u--input v-model="oilNameList" placeholder="根据选择的订单回显" border="none" :disabled="true"
								disabledColor="#fff"></u--input>
						</u-form-item>

						<u-form-item required label="油脂种类" borderBottom labelWidth="100">
							<u--input v-model="categoryNameList" placeholder="根据选择的订单回显" border="none" :disabled="true"
								disabledColor="#fff"></u--input>
						</u-form-item>
						<u-form-item required label="入库重量" borderBottom labelWidth="100">
							<u--input v-model="weightAll" placeholder="根据选择的订单回显" border="none" :disabled="true"
								disabledColor="#fff"></u--input>
						</u-form-item>
					</template>
					<u-form-item v-if="form.source == '1'" required prop="oilSource" label="油品来源" borderBottom labelWidth="100">
						<u--input v-model="form.oilSource" placeholder="请输入" border="none"></u--input>
					</u-form-item>
				</u--form>
			</view>
			<template v-if="form.source == '0'">
				<view class="relatedOrder-box">
					<view class="title">
						相关订单 <view class="text">（请选择入库日期和司机）</view>
					</view>
					<view class="order-list" v-if="OrderListByReceipt.length">
						<view v-for="(item,index) in OrderListByReceipt" :key="index"  class="item-info">
							<view class="item-title flex-ac flex-jb l-border-bottom">
								<view>订单号：{{ item.orderCode }}</view>
								<!-- <view>{}}</view> -->
							</view>

							<view class="form l-border-bottom">
								<view class="form-type">
									<view>{{item.emissionUnitName}}</view>
								</view>
								<view class="form-item">
									<view>接收单位：</view>
									<view>{{ item.recycleBinName }}</view>
								</view>
								<view class="form-item">
									<view>车牌号：</view>
									<view>{{ item.licensePlateNumber }}</view>
								</view>
								<view class="form-item">
									<view>派单时间：</view>
									<view>{{ item.dispatchTime }}</view>
								</view>
							</view>
						</view>
					</view>
					<view class="" style="text-align: center;" v-else>
						无订单
					</view>
				</view>
				
			</template>
			<template v-if="form.source == '1'">
				<view v-for="(item, index) of form.detailsList" :key="index">
					<view class="title flex-jb">
						<view>信息{{ index + 1 }}</view>
						<view v-if="index" class="delete" @click="delData(index)">删除</view>
					</view>
					<view class="form">
						<u--form labelPosition="left" :model="item"  :ref="`form${index}`"
							labelWidth="100">
							<u-form-item required label="油品信息" prop="item.oilId" borderBottom>
								<LSelect border="none" v-model="item.oilId" dataKey="oilName" dataValue="id"
									:localdata="oilAllList" @change="oilSelect" :isIndex="true"  :indexNum="index"></LSelect>
							</u-form-item>
							<u-form-item required label="油脂种类" prop="item.oilId" borderBottom>
								<LSelect border="none"  v-model="item.categoryId" dataKey="typeName" dataValue="id" 
								:localdata="item.categoryAllList" ></LSelect>
								
							</u-form-item>
							<u-form-item label="桶数" required prop="item.barrelsNumber" borderBottom>
								<u--input v-model="item.barrelsNumber" border="none" placeholder="请输入" type="number"></u--input>
							</u-form-item>
							<u-form-item label="重量（kg）" prop="item.weight" borderBottom labelWidth="120">
								<u--input v-model="item.weight" border="none" placeholder="请输入" type="number"></u--input>
							</u-form-item>
						</u--form>
					</view>
				</view>
			</template>

			<view class="button">
				<view class="button2" @click="addData" v-if="form.source == '1'">添加</view>
				<view class="button1" @click="submit">确认入库</view>
			</view>
		</view>

		<u-popup :show="tongjiOpen" mode="center" :round="10" @close="tongjiOpen = false" :safeAreaInsetBottom="false">
			<view class="popup-box">
				<view class="box">
					<view class="title">确认入库统计</view>
					<view class="list">
						<view class="item">
							<view class="text">油品信息</view>
							<view class="label">
								<view class="label" v-for="(item,index) in taskTotalData.oilList">
									{{ item.oilName }}--{{ item.actualWeight }}kg
								</view>
							</view>
						</view>
						<view class="item">
							<view class="text">入库重量：</view>
							<view class="label">{{taskTotalData.oilWeight || '0'}}kg</view>
						</view>
						<view class="item">
							<view class="text">重量误差：</view>
							<view class="label">{{ taskTotalData.weightError || '0'}}kg</view>
						</view>
					</view>
					<view class="title">称重信息</view>
					<view class="list">
						<view class="item">
							<view class="text">地磅称重重量：</view>
							<view class="label">{{ taskTotalData.weighbridgeWeight || '0'}}kg</view>
						</view>
					</view>
				</view>
				<view class="btn" @click="submit1">
					确认入库
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		category_allList,

		oil_allList,
		listAllTransfer_station,
		// addLn_receipt_shipment_order,
	} from "@/api/transport.js";
	import {
		getDriverList,
		getOrderListByReceipt,
		addNewReceiptDoc,
		getTaskTotalWeight
	} from "@/api/warehousing.js";
	import LSelect from "@/components/LSelect";
	export default {
		components: {
			LSelect
		},
		data() {
			return {
				// 来源
				source_type: [{
						value: '0',
						label: '线上'
					},
					{
						value: '1',
						label: '线下'
					}
				],
				transferAllList: [], //中转站
				driverAllList: [], //司机列表
				oilAllList: [], //油品列表
				categoryAllList:[],
				selectDriverId: '', //选择的司机的id 筛选列表
				// 表单校验
				rules: {
					source: [{
						required: true,
						message: "请选择来源",
						trigger: "blur"
					}],
					// receiptLocationId: [{
					// 	required: true,
					// 	message: "请选择入库地点",
					// 	trigger: "blur"
					// }],
					indate: [{
						required: true,
						message: "请选择入库日期",
						trigger: "blur"
					}],
					oilSource: [{
						required: true,
						message: "请输入油品来源",
						trigger: "blur"
					}],
					oilSource: [{
						required: true,
						message: "请选择司机",
						trigger: "blur"
					}],
				},
				form: {
					indate: null,
					source: null, //来源 0线上/1线下
					receiptLocationId: null, //入库地点id
					oilSource: null, //油品来源
					quantity: null, //数量/重量
					transactionOrderCode: null, //订单id,逗号分割
					indate: null,
					// errorStatus: null, //误差状态，正常、负偏差、正偏差
					detailsList: [{
						oilId: null, //油品id
						categoryId:null,
						barrelsNumber: null, //预估桶数
						weight: null, //预估重量
						categoryAllList:[],
					}],
					remark: null,
				},

				OrderListByReceipt: [],
				oilNameList: '',
				categoryNameList: '',
				weightAll: '',

				tongjiOpen: false,
				taskTotalData: [],


			};
		},
		watch: {
			// 订单列表
			OrderListByReceipt(newValue, oldValue) {
				// //taskId,逗号分割
				this.form.transactionOrderCode = newValue.map((item, index) => {
					return item.taskId;
				}).join(",");

				this.oilNameList = newValue.map((item, index) => {
					return item.oilName;
				}).join(",");
				this.categoryNameList = newValue.map((item, index) => {
					return item.categoryName;
				}).join(",");
				let sum = 0
				newValue.forEach(item => {
					sum += item.weight;
				});
				this.weightAll = sum
			}
		},
		onLoad(option) {
		},
		onShow() {
			if (uni.getStorageSync('token')){
				this.$store.dispatch("actionGetUserInfo");
			}
			this.getTransferAllList()
			this.getDriverList()
			this.getOilList()
		},
		methods: {
			// 日期选择
			transportationTimeChange(e) {
				this.form.indate = e.detail.value;
				this.getOrderListByReceipt()
				// this.$set(this.form, 'indate', e.detail.value); // 使用 Vue.set
			},
			// 查询所有中转站
			getTransferAllList() {
				listAllTransfer_station().then((response) => {
					this.transferAllList = response.data;
					if(this.userInfo.userId){
						this.form.receiptLocationId = this.userInfo.userId
					}
				});
			},
			// 查询所有司机 getDriverList
			getDriverList() {
				getDriverList().then((response) => {
					this.driverAllList = response.data;
				});
			},
			// 油品列表
			getOilList() {
				oil_allList().then((response) => {
					this.oilAllList = response.data;
				});
			},
			// 选择油品，根据油品获取种类
			// oilSelect(id){
			// 	category_allList({
			// 		oilId:id
			// 	}).then((response) => {
			// 		this.categoryAllList = response.data;
			//   });
			// },
			oilSelect(e){
				console.log('oilSelect',e)
				let index = e.index
				category_allList({
					oilId:e.id
				}).then((response) => {
					// this.categoryAllList = response.data;
					let isTrue = response.data.find(item => item.id == this.form.detailsList[index].categoryId)
					if(!isTrue){
					  this.form.detailsList[index].categoryId = ''
					}
					this.form.detailsList[index].categoryAllList = [...response.data];
					// 此处是更新视图操作
					let newData = this.form.detailsList[index]
					this.form.detailsList.splice(index,1,newData)
			  });
			},
			// 入库单查询收运订单列表 indate driverid
			getOrderListByReceipt(e) {
				console.log(e);
				if (!this.form.indate) {
					uni.$u.toast('请您选择入库日期');
					return
				}
				 // if(!this.selectDriverId && !e){
				 //  uni.$u.toast('请您选择司机');
					// return
				 // }
				getOrderListByReceipt({
					indate: this.form.indate,
					driverId: this.selectDriverId || e,
				}).then(res => {
					this.OrderListByReceipt = res.data;
				})
			},

			addData() {
				let arr = {
					oilId: null, //油品id
					categoryId:null,
					barrelsNumber: null, //桶数
					weight: null, //重量
					categoryAllList:[],
				}
				this.form.detailsList.push(arr);
			},
			delData(index) {
				this.form.detailsList.splice(index, 1);
			},
			submit() {
				this.form.receiptLocationId = this.userInfo.userId
				this.$refs.uForm.validate().then((res) => {
					if (this.form.source == '0') {
						if(!this.selectDriverId){
							uni.$u.toast('请选择司机');
							return false
						}
						if(!this.OrderListByReceipt.length){
							uni.$u.toast('当前无相关订单');
							return false
						}
						// 如果是线上，显示提示框
						let taskId = this.OrderListByReceipt[0].taskId || ''
						getTaskTotalWeight(taskId).then(res => {
							this.taskTotalData = res.data
							this.tongjiOpen = true
						})
					} else {
						// this.form.detailsList.forEach((item,index) => {  })
						for(let i = 0; i < this.form.detailsList.length; i++){
							const item = this.form.detailsList[i]
							if(!item.oilId){
								uni.$u.toast('请选择油品信息');
								return false
							}
							if(!item.categoryId){
								uni.$u.toast('请选择油脂种类');
								return false
							}
							if(!item.barrelsNumber){
								uni.$u.toast('请输入桶数');
								return false
							}
						}
						addNewReceiptDoc(this.form).then(res => {
							uni.$u.toast('添加成功');
							this.goLink('', 'back')
						})
					}
				});
				

			},
			submit1() {
				addNewReceiptDoc({
					...this.form,
					quantity: this.taskTotalData.weighbridgeWeight,
					weightError: this.taskTotalData.weightError,
					oilWeight: this.taskTotalData.oilWeight,
					taskId:this.OrderListByReceipt[0].taskId,
					driverId:this.selectDriverId,
				}).then(res => {
					this.tongjiOpen = false;
					uni.$u.toast('添加成功');
					this.goLink('', 'back')
				})
			},

		},
	};
</script>

<style lang="less" scoped>
	.add-collection {
		padding: 30rpx 30rpx 0 30rpx;

		.title {
			font-size: 30rpx;
			color: #000;
			margin: 28rpx 0 20rpx 0;

			.delete {
				color: #138e57;
			}
		}

		.form {
			padding: 0 30rpx;
			background: #ffffff;
			border-radius: 16rpx;
		}

		.button {
			margin: 0 40rpx;
			padding: 80rpx 0;
		}

		.button1 {
			color: #ffffff;
			margin-top: 30rpx;
			background: linear-gradient(83deg, #48b453 0%, #2c9f79 100%);
		}

		.button2 {
			color: #138e57;
			border: 2rpx solid #138e57;
		}

		.button1,
		.button2 {
			padding: 24rpx;
			text-align: center;
			border-radius: 200rpx;
			font-size: 32rpx;
		}
	}

	.relatedOrder-box {
		padding: 0 30rpx;

		.title {
			display: flex;
			align-items: center;
			font-size: 34rpx;
			color: #000000;
			padding: 30rpx 0;

			.text {
				font-size: 28rpx;
				color: #666;
			}
		}

		.order-list {}

		.item-info {
			margin-bottom: 30px;
			padding: 20rpx 30rpx 30rpx 30rpx;
			background: #fff;
			border-radius: 12rpx;

			.button-deep {
				border-radius: 200rpx;
				padding: 16rpx 0;
				margin: 20rpx 0 0 20rpx;
				width: 171rpx;
				text-align: center;
				background: linear-gradient(83deg, #48b453 0%, #2c9f79 100%);
				color: #ffffff;
			}

			.item-title {
				padding-bottom: 20rpx;

				view:nth-child(1) {
					font-size: 30rpx;
					color: #000000;
				}

				view:nth-child(2) {
					font-size: 28rpx;
				}
			}

			.form {
				padding: 30rpx 0;

				.form-type {
					font-size: 32rpx;
					color: #000000;
				}

				.form-item {
					display: flex;
					font-size: 30rpx;
					padding-top: 16rpx;

					view:nth-child(2) {
						color: #000;
					}
				}
			}
		}
	}

	.popup-box {
		width: 80vw;
		padding: 30rpx 0;

		.box {
			padding: 0 30rpx;

			.title {
				font-size: 35rpx;
				color: #2E2528;
				margin-bottom: 40rpx;
			}

			.list {
				margin-bottom: 80rpx;

				.item {
					margin: 30rpx 0;
					display: flex;
					line-height: 37rpx;

					.text {
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #666668;
					}

					.label {
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #000;
					}
				}
			}

		}

		.btn {
			margin-top: 60rpx;
			padding-top: 30rpx;
			border-top: 1px solid rgba(0, 0, 0, 0.10);
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 35rpx;
			color: #138E57;
			text-align: center;
		}
	}
</style>